package core.ImgUpload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ImgUpLoadAction extends ActionSupport
{
	
	/*
	 * 调用此方法，传入一个项目中文件名的字符串，如："/img"
	 * 自动把图片存放到服务器所对应的目录下
	 **/
	public ArrayList<String> upload(String loact,List<File> file,List<String> fileFileName,List<String> fileContextType) throws IOException
	{
		//获取到文件存放路径的物理地址
		String file_locate = ServletActionContext.getServletContext().getRealPath(loact);
		ArrayList<String> img_name = new ArrayList<String>();
		
		/*检测存储位置目标文件是否存在，不存在则自动创建*/
		if(loact==null) return null;
		else
		{
			File file1 = new File(file_locate); // new File(path+"/"+"imgs");
			file1.mkdirs();
		}
		
		
		for(int i =0 ; i<file.size() ; i++)
		{
			/*采取的存储名称为  本地时间（精确到毫秒）*/
			Calendar cal = Calendar.getInstance();
		    Date date = cal.getTime();
		    String filename = new SimpleDateFormat("MMddHHmmssSSS").format(date);
		    
		    /*截取上传图片的后缀名*/
		    String value = fileFileName.get(0);
			int star = value.lastIndexOf(".");
			filename = filename+value.substring(star,value.length());//截取上传的文件的后缀名，再和前面生成的日期拼接起来
			
			//取到临时文件的图片,建立输出流，输出到此处 
			InputStream is = new FileInputStream(file.get(i));
			
			//取到临时文件的图片名称,建立输出流
			File outputfile = new File(file_locate,filename);
			OutputStream os = new FileOutputStream(outputfile);
			
			
			byte[] buff = new byte[400] ;//从输入流输出到输出流，最终到目标文件
			int length = 0;
			while( -1 != (length = (is.read(buff)) ) )
			{
				os.write(buff, 0, length);
			}
			is.close();
			os.close();
			
			img_name.add(filename);
		}
		
		
		return img_name;
	}
}
